package cn.bincker.mybatis.encrypt.converter.impl;

import cn.bincker.mybatis.encrypt.exception.InvalidDataException;

import java.nio.ByteBuffer;

public class ShortEncryptConverter extends BaseEncryptConverter<Short> {
    @Override
    public Short convertNonNull(byte[] data) {
        if (data.length >= Long.BYTES){
            return (short) ByteBuffer.wrap(data).getLong();
        } else if (data.length >= Integer.BYTES){
            return (short) ByteBuffer.wrap(data).getInt();
        } else if (data.length >= Short.BYTES){
            return ByteBuffer.wrap(data).getShort();
        }
        throw new InvalidDataException("short need " + Short.BYTES + " bytes but got " + data.length);
    }

    @Override
    public byte[] convertNonNull(Short object) {
        byte[] result = new byte[Short.BYTES];
        ByteBuffer.wrap(result).putShort(object);
        return result;
    }
}
